import datetime
import logging

import baostock as bs
import pymysql

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s | %(filename)s - {%(lineno)d} - [%(levelname)s] - %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S', encoding='utf-8')

mysql_host = "127.0.0.1"
mysql_port = 3306

# create mysql connect
connect = pymysql.connect(host=mysql_host, port=mysql_port, user='root', passwd='hxsoft.net', database='stock')
cursor = connect.cursor()

logging.info("truncate table stock.stock_code")
cursor.execute("truncate table stock.stock_code")
connect.commit()

lg = bs.login()
logging.info("fetch stock_code from api")

dayTime = datetime.date.strftime(datetime.date.today(), "%Y-%m-%d")
rs = bs.query_all_stock(day="2025-11-19")
while (rs.error_code == '0') & rs.next():
    # 获取一条记录，将记录合并在一起
    stock_list = rs.get_row_data()
    code = stock_list[0]
    name = stock_list[2]
    code_type = code[:2]
    code_value = code[3:5]
    stock_code = code[3:]
    if (code_type == 'sh' and (code_value == '60' or code_value == '68')) or (
            code_type == 'sz' and (code_value == '00' or code_value == '30')):
        sql = "insert into stock.stock_code values ('%s','%s')" % (stock_code, name)
        cursor.execute(sql)
        connect.commit()

logging.info("fetch stock_code successful")

bs.logout()
